//index.js
//获取应用实例
const app = getApp()
const api  = require('./../../api/api.js')
const config=require('./../../api/config.js');
Page({
  data: {
    val: "",
    statusIsPlay: false,
    iconClass: ['icon-iconset0481', 'icon-iconset0482'],
    itemLrcUrl: "",
    itemLrc: "",
    itemTime: "00:00",
    marginTop: 0,
    currentIndex222: 0,
    animation: "",
    searchList: [{
      title: "歌曲名",
      author: "歌手",
      pic: './../../images/bg.png',
      url: ''
    }],
    currentPlay: 0
  },
  //事件处理函数
  changeVal(e) { // 更改input输入框内容
    if (e.detail && e.detail.value) {
      this.setData({
        val: e.detail.value
      });
    }
  },
  playItem(e) { /**加载列表中的某一项 */
    let index = e.target.dataset.index || e.currentTarget.dataset.index;
    if (this.data.searchList[0].url === '') { /** 默认数据不进行加载播放 */
      return false;
    }
    if (index === this.data.currentPlay) { /**点击当前播放项 */
      let status = this.data.statusIsPlay;
      this.setData({
        statusIsPlay: !status
      });
      this.data.statusIsPlay ? this.audio.play() : this.audio.pause();
      return false;
    }
    this.iniData();
    this.setData({
      currentPlay: index,
      statusIsPlay: true,
      itemLrcUrl: this.data.searchList[index].lrc
    });
    //获取歌词
    this._getLrc();
    this.audio.stop();
    this.audio.src = "";
    this.audio.src = this.data.searchList[index].url;
    this.audio.play();
  },
  _getLrc() { //通过url获取歌词信息
    let url = this.data.searchList[this.data.currentPlay].lrc;
    if (url) {
      api.getLrc(url).then((res) => {
        this.setData({
          itemLrc: this._sliceNull(this.parseLyric(res.data))
        })
      });
    } else {
      this.setData({
        itemLrc: [
          ['0.00', "暂无歌词"]
        ]
      });
    }
  },
  send() { //搜索按钮事件
  let _this=this;
    let _val = _this.data.val.replace(/(^\s*)|(\s*$)/g, "")
    _this.setData({ val: _val});
    if (_this.data.val === "" || _this.data.val===undefined){
      wx.showToast({
        title: config.TOAST.BLANK,
        icon: "none",
        complete: function () {
          setTimeout(() => {
            wx.hideToast();
          }, 1000)

        }
      })
    return false;
  }
    _this._loadShow();
    api.getSearchList(_this.data.val).then((res) => {
      if (res.statusCode >= 200 && res.statusCode <= 299) {
        _this.setData({
          searchList: res.data.Body,
          currentPlay: 0,
          statusIsPlay:false
        });
        _this.iniData();
        _this.audio.src = _this.data.searchList[_this.data.currentPlay].url;
        _this._getLrc();
        _this._loadHide();
      }
    }).catch((err) => {
      console.error(config.CONST.ERR_E + err);
    });
  },
  switchIco() { /**播放暂停控制按钮 */
    if (this.data.searchList[0].url === '') { /** 默认数据不进行加载播放 */
      return false;
    }
    if (this.data.statusIsPlay) {
      this.setData({
        statusIsPlay: false
      });
      this.audio.pause();
    } else {
      this.setData({
        statusIsPlay: true
      });
      this.audio.play();

    }
  },
  downFile() { /**下载文件 */
    /*let url = this.data.searchList[this.data.currentPlay].url;
    if (url) {
      url += "&size=m4a";
      api.getFile(url).then((res) => {
        if (res.statusCode === 200) {
          wx.saveFile({
            tempFilePath: res.tempFilePath,
            success(res) {
              console.log(config.CONST.FILE_SUCE + res.savedFilePath);
            },
            fail(err) {
              console.log(config.CONST.FILE_ERR + JSON.stringify(err));
            }
          })
        }
      }).catch((err) => {
        console.log(config.CONST.DOWN_ERR + err);
      });
    }*/
    wx.showToast({
      title: config.TOAST.TITLE,
      icon:"none",
      complete:function(){
        setTimeout(()=>{
          wx.hideToast();
        },1000)
        
      }
    })
    

  },
  iniData() {
    this.setData({
      itemLrc: "",
      marginTop: 0,
      currentIndex222: 0,
      itemTime: "00:00"
    });
  },
  parseLyric(text) { //将歌词按时间分化
    let result = [];
    let lines = text.split('\n'),
      pattern = /\[\d{2}:\d{2}.\d+\]/g;
      
    while (lines.length>0&&!pattern.test(lines[0])) {
      lines = lines.slice(1);
    };
    if (lines.length <= 0){
      return text.split('\n');
    }
    //上面用'\n'生成数组时，结果中最后一个为空元素，这里将去掉
    lines[lines.length - 1].length === 0 && lines.pop();
    lines.forEach(function(v /*数组元素值*/ , i /*元素索引*/ , a /*数组本身*/ ) {
      //提取出时间[xx:xx.xx] 
      let time = v.match(pattern),
        //提取歌词 
        value = v.replace(pattern, '');
      // 因为一行里面可能有多个时间，所以time有可能是[xx:xx.xx][xx:xx.xx][xx:xx.xx]的形式，需要进一步分隔
      time.forEach(function(v1, i1, a1) {
        //去掉时间里的中括号得到xx:xx.xx
        var t = v1.slice(1, -1).split(':');
        //将结果压入最终数组
        result.push([parseInt(t[0], 10) * 60 + parseFloat(t[1]), value]);
      });
    });
    //最后将结果数组中的元素按时间大小排序，以便保存之后正常显示歌词
    result.sort(function(a, b) {
      return a[0] - b[0];
    });
    return result;
  },
  _sliceNull(lrc) { //清除数组中的空格
    var result = []
    for (var i = 0; i < lrc.length; i++) {
      if (lrc[i][1] == "") {
        continue;
      } else {
        result.push(lrc[i]);
      }
    }
    return result
  },
  _loadShow(){
    wx.showLoading({
      title: config.LOAD.LOADING
    });
  },
  _loadHide(){
    wx.hideLoading();
  },
  changeItemTime(time) {
    let m = parseInt(time / 60);
    m = (m < 10) ? ('0' + m % 60) : (m % 60);
    let s = ((time % 60) < 10) ? ('0' + time % 60) : (time % 60);
    return m + ':' + s;

  },
  onLoad() {
    let _this = this;
    _this.audio = wx.createInnerAudioContext();
    _this.audio.onPlay(() => {

      _this.audio.onTimeUpdate(function() {
        _this.setData({
          itemTime: _this.changeItemTime(parseInt(_this.audio.currentTime))
        });
        if (_this.data.currentIndex222 >= 6) { //超过6行开始滚动
          _this.setData({
            marginTop: (_this.data.currentIndex222 - 6) * 20
          })
        }
        // 文稿对应行颜色改变
        if (_this.data.currentIndex222 != _this.data.itemLrc.length - 1) {
          var j = 0;
          for (var j = _this.data.currentIndex222; j < _this.data.itemLrc.length; j++) {
            // 当前时间与前一行，后一行时间作比较， j:代表当前行数
            if (_this.data.currentIndex222 == _this.data.itemLrc.length - 2) {
              //最后一行只能与前一行时间比较
              if (parseFloat(_this.audio.currentTime) > parseFloat(_this.data.itemLrc[_this.data.itemLrc.length - 1][0])) {
                _this.setData({
                  currentIndex222: _this.data.itemLrc.length - 1
                })
                return;
              }
            } else {
              if (parseFloat(_this.audio.currentTime) > parseFloat(_this.data.itemLrc[j][0]) && parseFloat(_this.audio.currentTime) < parseFloat(_this.data.itemLrc[j + 1][0])) {
                _this.setData({
                  currentIndex222: j
                })
                return;
              }
            }
          }

        }
      });
     

    });
    _this.audio.onWaiting(()=>{
      _this._loadShow();
    });
    _this.audio.onCanplay(()=>{
      _this._loadHide();
    })
  }
})